import process from "process";
import * as step from '@flow-step/step-toolkit'

const FLOW_JOB_TOKEN: string = 'FLOW_JOB_TOKEN'

export async function dockerLogin(aliyunRegion: string, instanceName: string, useVpcAddress: boolean): Promise<void> {
    const serviceConnectionId = process.env["SERVICE_CONNECTION_ID"];
    if (serviceConnectionId == undefined) {
        throw new Error('missing SERVICE_CONNECTION_ID')
    }

    const flowJobToken: string | undefined =
        process.env[FLOW_JOB_TOKEN]

    if (flowJobToken == undefined) {
        throw new Error('missing FLOW_JOB_TOKEN')
    }

    const dockerACREECertificate = await step.certificate.getDockerAcrEnterpriseCertificate(flowJobToken, serviceConnectionId as string, aliyunRegion, instanceName);
    if (dockerACREECertificate == undefined || dockerACREECertificate.username == undefined) {
        throw new Error(`get getDockerAcrEnterpriseCertificate but error: ${JSON.stringify(dockerACREECertificate)}`)
    }

    const dockerUsername = dockerACREECertificate.username
    const dockerPassword = dockerACREECertificate.password

    if (dockerUsername == undefined || dockerPassword == undefined) {
        throw new Error('missing docker username or password')
    }

    let dockerRepository = "";
    if (useVpcAddress && process.env["NODEGROUP_TYPE"] !== "K8S") {
        dockerRepository = `${instanceName}-registry-vpc.${aliyunRegion}.cr.aliyuncs.com`;
    } else {
        dockerRepository = `${instanceName}-registry.${aliyunRegion}.cr.aliyuncs.com`;
    }

    step.info(`ready to execute: docker login -u ${dockerUsername} -p **** ${dockerRepository}`)
    const loginResultCode = await step.exec.call('docker', ['login', '-u', dockerUsername, '-p', dockerPassword, dockerRepository], {
        listener: {
            stdoutLine: (line: string) => {
                step.info(line)
            },
            stderrLine: (line: string) => step.info(line),
        }
    })

    if (loginResultCode != 0) {
        throw new Error(`docker login -u ${dockerUsername} -p **** ${dockerRepository} but error`)
    }
}